const express = require("express");
const { check, validationResult } = require('express-validator')

const { db, genid } = require("../db/DbUtils.js")
const { jwts } = require("../utils/JsonWebtoken.js")
const { checks } = require("../utils/Validator.js")
const { EPSTATE } = require("../config/state.json")

const router = express.Router();



// 分类查询
router.get("/", async(req, res) => {


    const sql_all = "select * from `blog_category`"

    let { err, rows } = await db.async.query(sql_all, [])

    res.send({
        rows
    })

})


// 文章删除
router.delete("/delete", async(req, res) => {


    // token验证
    let token = req.headers.authorization
    let user_id = jwts.verifyToken(token)
    if (user_id === null || user_id === undefined) {
        res.send(EPSTATE.TOKENINF)
        return
    }

    let blog_category_id = req.query.blog_category_id


    // SQL操作
    const sql_blog = "delete from `blog_category` where `blog_category_id` = ?";
    let { err, rows } = await db.async.query(sql_blog, blog_category_id)


    if (err === null) {
        res.send("删除成功")
    } else {
        console.log(err);
        res.send("删除失败")
    }

})


// 分类增加
router.post("/upload", checks.categoryUpload(), async(req, res) => {

    // 表单验证
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }

    // token验证
    let token = req.headers.authorization
    let user_id = jwts.verifyToken(token)
    if (user_id === null || user_id === undefined) {
        res.send(EPSTATE.TOKENINF)
        return
    }

    let { blog_category_name } = req.body
    let blog_category_id = genid.NextId();

    // SQL操作
    const sql_blog = "INSERT INTO `blog_category`(`blog_category_id`, `blog_category_name`) VALUES (?, ?)"
    let params = [blog_category_id, blog_category_name]
    let { err, rows } = await db.async.query(sql_blog, params)


    if (err === null) {
        res.send(EPSTATE.EP200)
    } else {
        res.send(EPSTATE.SQLINF)
    }

})

module.exports = router